package top.littlejiang.onlinexam.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.configuration.SystemConfig;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.common.utils.PasswordUtils;
import top.littlejiang.onlinexam.common.utils.UUIDUtil;
import top.littlejiang.onlinexam.service.OlexamFileService;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author chen
 * @Description
 * @since 2021/2/28 12:09
 */
@Slf4j
@Service
public class OlexamFileServiceImpl implements OlexamFileService {

    @Autowired
    SystemConfig config;

    /**
     * 根据图片名返回图片
     *
     * @param imageName
     * @return
     */
    @Override
    public BufferedImage getImage(String imageName) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(new FileInputStream(new File(config.getPicturePath() + imageName)));
        } catch (Exception e) {
            if (e instanceof IOException){
                log.error(e.toString(), e);
                throw new BusinessException("图片加载失败");
            }
            if (e instanceof FileNotFoundException){
                log.error(e.toString(), e);
                throw new BusinessException("找不到图片！");
            }
        }
        return image;
    }

    /**
     *
     * @param file
     * @return string 可访问的全路径
     */
    @Override
    public String saveFile(MultipartFile file, String urlPrefix) {
        String name = file.getOriginalFilename();
        //获取后缀
        String suffix = name.substring(name.lastIndexOf("."));
        //构造文件名
        String fileName = UUIDUtil.getUUID();
        //图片访问URI(即除了协议、地址和端口号的URL)
        String urlPath = urlPrefix + fileName + suffix;
        //图片保存路径
        String savePath = config.getPicturePath() + fileName + suffix;
        File saveFile = new File(savePath);
        if (!saveFile.exists()){
            saveFile.mkdirs();
        }
        try {
            //将临时存储的文件移动到真实存储路径下
            file.transferTo(saveFile);
        } catch (IOException e) {
            log.error(e.toString(), e);
            throw new BusinessException("文件上传失败！");
        }
        return config.getServerAddress() + urlPath;
    }
}
